package com.wolfalpha.utron.activity;

import android.os.Bundle;
import android.os.Handler;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseActivity;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.bean.InitRequirement;
import com.wolfalpha.utron.bean.UserInfo;
import com.wolfalpha.utron.service.ReuirementService;
import com.wolfalpha.utron.service.impl.RequirementServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.ThreadPoolUtils;

/**
 * 初始化界面
 * <p/>
 * 检测是否快速登录
 * <p/>
 * 展示初始化界面的图片
 * <p/>
 * Created by luodon on 15/8/20.
 */
public class InitActivity extends BaseActivity implements View.OnClickListener {

    private InitRequirement requirement;        //存储需求实体

    private ImageView ivAd;                 //广告图片
    private LinearLayout llRequire;       //需求穿越布局
    private TextView tvRequire;             //需求内容
    private ImageView cbYes;                 //赞同
    private ImageView cbNo;                  //反对

    private TextView tvTime;                //剩余选择时间

    private TextView tvJump;                   //跳过

    private int leftTime = 5;               //5秒选择时间

    private final static int GO_SHOW_REQUIRE = 1;   //显示需求
    private final static int GO_SHOW_TIME = 3;      //更新时间
    private final static int GO_DO_LOGO = 2;        //登录
    private final static int CHECK_YES = 4;         //选择了YES
    private final static int CHECK_NO = 5;          //选择了NO

    private ReuirementService reuirementService;    //需求服务

    private int checked = -1;

    private int state = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /**
         * 打开应用调试
         */
        AppContext.getInstance().setDebug(true);


        reuirementService = new RequirementServiceImpl();

        if (AppContext.getInstance().getProperty("nofirst") == null || !AppContext.getInstance().getProperty("nofirst").equals("true")) {
            //第一次打开应用
            state = 0;
        } else {
            if (AppContext.getInstance().getIsLogined() == false) {
                //没有登录过
                state = 1;
            } else {
                //已登录
                state = 2;
            }
        }


        if (state == 0) {
            //跳到引导页
            UIHelper.showActivityAndFinish(InitActivity.this, GuideActivity.class);
            return;
        }

        if (state == 1) {
            //跳到登录页
            UIHelper.showActivityAndFinish(InitActivity.this, LoginActivity.class);
            return;
        }

        /**
         * 初始化个人信息
         */

        try {
            AppContext.getInstance().initUserInfo((UserInfo) AppContext.getInstance().readObject("userInfo"));
        } catch (Exception e) {
            e.printStackTrace();
            UIHelper.showActivityAndFinish(InitActivity.this, LoginActivity.class);
            return;
        }
        AppContext.getInstance().initializeContacts();

        setContentView(R.layout.activity_init);
        initView();
        loadData();
        initListeners();
    }

    /**
     * 加载网络数据（获取需求）
     */
    private void loadData() {
        //本地生产访问网络请求需求的概率 80% by Version1.0
        double rand = Math.random();    //random:0~1
        if (rand > 0.618) {//0.618
            ThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    requirement = reuirementService.getOne();
                    if (requirement != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                showRequire();
                            }
                        });
                        Runnable runnable = new Runnable() {
                            @Override
                            public void run() {
                                if (leftTime <= 0) {
                                    show();
                                    return;
                                }
                                leftTime--;
                                tvTime.setText(leftTime + "秒");
                                handler.postDelayed(this, 1000);
                            }
                        };
                        handler.post(runnable);
                    } else {
                        jumpNext(0);
                    }
                }
            });
        } else {
            jumpNext(1);
        }


    }

    Handler handler = new Handler();

    /**
     * 单一选择
     *
     * @param i
     */
    private void checkAnswer(final int i) {
        if (i == 1) {
            cbYes.setBackgroundResource(R.mipmap.init_yes_checked);
            cbNo.setBackgroundResource(R.mipmap.init_no_normal);
        } else if (i == 2) {
            cbYes.setBackgroundResource(R.mipmap.init_yes_normal);
            cbNo.setBackgroundResource(R.mipmap.init_no_checked);
        }

    }

    /**
     * 跳转到下一页
     */
    private void jumpNext(final int i) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000 * i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            show();
                        }
                    });
                }
            }
        }).start();
    }

    private void showRequire() {
        llRequire.setVisibility(View.VISIBLE);
        tvTime.setText(String.valueOf(leftTime) + "秒");
        tvRequire.setText(requirement.getContent());
    }

    @Override
    protected void onStop() {
        super.onStop();

    }


    /**
     * 跳转
     */
    private void show() {
        UIHelper.showActivityAndFinish(InitActivity.this, MainActivity.class);
    }

    /**
     * 初始化界面
     */
    private void initView() {
        llRequire = (LinearLayout) findViewById(R.id.ll_init_require);
        tvRequire = (TextView) findViewById(R.id.tv_init_require);
        tvTime = (TextView) findViewById(R.id.tv_init_time);

        tvJump = (TextView) findViewById(R.id.tv_init_require_jump);

        cbYes = (ImageView) findViewById(R.id.cb_init_yes);
        cbNo = (ImageView) findViewById(R.id.cb_init_no);
    }


    /**
     * 初始化监听器
     */
    private void initListeners() {
        cbNo.setOnClickListener(this);
        cbYes.setOnClickListener(this);
        tvJump.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        //leftTime = -1;
        if (checked != -1) return;
        switch (v.getId()) {
            case R.id.cb_init_yes:
                checked = 1;
                checkAnswer(1);
                break;
            case R.id.cb_init_no:
                checked = 2;
                checkAnswer(2);
                break;
            case R.id.tv_init_require_jump:
                //跳过需求调查
                tvJump.setClickable(false);
                break;
        }

        if (checked != -1) {
            //用户选择了答案
            ThreadPoolUtils.execute(new Runnable() {
                @Override
                public void run() {
                    reuirementService.doForOne(checked == 1 ? true : false, requirement.getId());
                }
            });
        }
    }
}
